//
//  ToastView.swift
//  ToastView-Swift
//
//  Copyright (c) 2015-2019 Charles Scalesse.
//
//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//MARK: - 来源 https://gitee.com/taobo0505/Toast-Swift.git

import UIKit
import ObjectiveC

/**
 ToastView is a Swift extension that adds toast notifications to the `UIView` object class.
 It is intended to be simple, lightweight, and easy to use. Most toast notifications
 can be triggered with a single line of code.
 
 The `makeToastView` methods create a new view and then display it as toast.
 
 The `showToastView` methods display any view as toast.
 
 */


// MARK: -default config
private let toastViewTag: Int = 910728;

private var defaultStyle: ToastViewStyle? = nil;

private var defaultStyleOne: ToastViewStyle = {
    var style = ToastViewStyle()
    style.backgroundColor = .black.withAlphaComponent(0.33)
    style.cornerRadius = 0.0
    style.displayShadow = false
    defaultStyle = style
    return style
}()


private let INTERVAL_KEYBOARD: Double = 10

class WrapperView: UIView {
    
    weak var _textFieldView: UIView?
    var _textFieldViewIntialFrame: CGRect?
    
    // 默认wapper view
    static func defaultView(_ frame: CGRect = CGRect(0, 0, Screen.width, Screen.height) , style: ToastViewStyle = defaultViewStyle()) -> WrapperView {
        let wrapperView = WrapperView()
        wrapperView.backgroundColor = style.backgroundColor
        wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
        wrapperView.layer.cornerRadius = style.cornerRadius
        if style.displayShadow {
            wrapperView.layer.shadowColor = UIColor.black.cgColor
            wrapperView.layer.shadowOpacity = style.shadowOpacity
            wrapperView.layer.shadowRadius = style.shadowRadius
            wrapperView.layer.shadowOffset = style.shadowOffset
        }
        wrapperView.frame = frame
        wrapperView.tag = toastViewTag;
        
        // 键盘弹出监听，解决键盘挡住输入框的问题
        NotificationCenter.default.addObserver(wrapperView, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil)
        
        NotificationCenter.default.addObserver(wrapperView, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        //
        NotificationCenter.default.addObserver(wrapperView, selector: #selector(textFieldViewDidBeginEditing), name: UITextField.textDidBeginEditingNotification, object: nil)
        
        return wrapperView
    }
}

/// 处理键盘问题
extension WrapperView {
    //键盘弹起
    @objc func keyboardWillAppear(notification: NSNotification) {
        // 获得软键盘的高
        let keyboardinfo = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey]
        let kbHeight: CGFloat = (keyboardinfo as AnyObject).cgRectValue.size.height
        
        let keyboardDurationInfo = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration: Double = (keyboardDurationInfo as AnyObject).doubleValue
        
        guard let textFieldViewIntialFrame = _textFieldViewIntialFrame else { return }
        
        let offset = textFieldViewIntialFrame.y + textFieldViewIntialFrame.height + INTERVAL_KEYBOARD - (Screen.height - kbHeight)
        UIView.animate(withDuration: duration) {
            if offset > 0 {
                self.frame = CGRect(0.0, -offset, Screen.width, Screen.height)
            }else {
                self.frame = CGRect(0.0, 0.0, Screen.width, Screen.height)
            }
        }
        
    }

    //键盘落下
    @objc func keyboardWillDisappear(notification: NSNotification){
        let keyboardDurationInfo = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration: Double = (keyboardDurationInfo as AnyObject).doubleValue
        //软键盘收起的时候恢复原始偏移
        UIView.animate(withDuration: duration) {
            self.frame = CGRect(0.0, 0.0, Screen.width, Screen.height)
        }
    }
    
    
    // 开始编辑
    @objc func textFieldViewDidBeginEditing(notification: NSNotification) {
        guard let textFieldView = notification.object as? UIView else { return }
        guard let window = UIApplication.shared.keyWindow else { return }
        _textFieldView = textFieldView
        _textFieldViewIntialFrame = textFieldView.convert(CGRect(0, self.y, textFieldView.width, textFieldView.height), to: window)
    }
    
}

extension WrapperView: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        guard let view = touch.view else { return false }
        if view.tag == toastViewTag {
            guard let v = view.subviews.first else { return true }
            let point = touch.location(in: v)
            if point.x > 0 && point.y > 0 && point.x < v.bounds.width && point.y < v.bounds.height {
                return false
            }
            return true
        }
        return false
    }
}

public extension UIView {
    
    /**
     Keys used for associated objects.
     */
    private struct ToastViewKeys {
        static var timer        = "com.toast-view-swift.timer"
        static var duration     = "com.toast-view-swift.duration"
        static var point        = "com.toast-view-swift.point"
        static var style        = "com.toast-view-swift.style"
        static var tap          = "com.toast-view-swift.tap"
        static var completion   = "com.toast-view-swift.completion"
        static var activeToastViews = "com.toast-view-swift.activeToastViews"
        static var queue        = "com.toast-view-swift.queue"
    }
    
    /**
     Swift closures can't be directly associated with objects via the
     Objective-C runtime, so the (ugly) solution is to wrap them in a
     class that can be used with associated objects.
     */
    private class ToastViewCompletionWrapper {
        let completion: ((Bool) -> Void)?
        
        init(_ completion: ((Bool) -> Void)?) {
            self.completion = completion
        }
    }
    
    private enum ToastViewError: Error {
        case missingParameters
    }
    
    private var activeToastViews: NSMutableArray {
        get {
            if let activeToastViews = objc_getAssociatedObject(self, &ToastViewKeys.activeToastViews) as? NSMutableArray {
                return activeToastViews
            } else {
                let activeToastViews = NSMutableArray()
                objc_setAssociatedObject(self, &ToastViewKeys.activeToastViews, activeToastViews, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return activeToastViews
            }
        }
    }
    
    private var queue: NSMutableArray {
        get {
            if let queue = objc_getAssociatedObject(self, &ToastViewKeys.queue) as? NSMutableArray {
                return queue
            } else {
                let queue = NSMutableArray()
                objc_setAssociatedObject(self, &ToastViewKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return queue
            }
        }
    }
    
    // MARK: - Show ToastView Methods
    
    
    static func defaultViewStyle() -> ToastViewStyle {
        return defaultStyleOne
    }
    
    // MARK: - 显示弹窗
    ///  弹出自定义view
    /// - Parameters:
    ///   - toast: 自定义view
    ///   - tap:  点击背景移除 默认无
    ///   - queueEnable: 是都有队列 默认有
    ///   - position: 显示位置 默认中间
    ///   - duration: 显示时长
    ///   - completion: 完成回调
    func showViewToast(_ toast: UIView, tap: Bool = false, queueEnable: Bool = true, position: ToastViewPosition = .center, duration: TimeInterval = TimeInterval(Int.max), style: ToastViewStyle = defaultViewStyle(), completion: ((_ didTap: Bool) -> Void)? = nil) {
        let point = position.centerPoint(forToastView: toast, inSuperview: self)
        showViewToast(toast, tap: tap, queueEnable: queueEnable, point: point, duration: duration, completion: completion)
   }
    
    func showViewToast(_ toast: UIView, tap: Bool = false, queueEnable: Bool = true, point: CGPoint, duration: TimeInterval = TimeInterval(Int.max), style: ToastViewStyle = defaultViewStyle(), completion: ((_ didTap: Bool) -> Void)? = nil) {
        
        // 添加默认背景
        let wrapperView = WrapperView.defaultView(self.bounds, style: style)
        wrapperView.addSubview(toast)
        toast.center = point;
        wrapperView.alpha = 0.0
        print(wrapperView)
        // 是否需要添加点击时间
        if tap {
           let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleViewToastTapped(_:)))
           wrapperView.addGestureRecognizer(recognizer)
           wrapperView.isUserInteractionEnabled = true
           wrapperView.isExclusiveTouch = true
           recognizer.delegate = wrapperView
        }
        
        objc_setAssociatedObject(wrapperView, &ToastViewKeys.completion, ToastViewCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        if queueEnable, activeToastViews.count > 0 {
          objc_setAssociatedObject(wrapperView, &ToastViewKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
          objc_setAssociatedObject(wrapperView, &ToastViewKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
          objc_setAssociatedObject(wrapperView, &ToastViewKeys.tap, NSNumber(value: tap), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
          objc_setAssociatedObject(wrapperView, &ToastViewKeys.style, style, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
          queue.add(wrapperView)
        } else {
          showViewToast(wrapperView, duration: duration)
        }
      }
       
   // MARK: - 点击事件
   @objc
   private func handleViewToastTapped(_ recognizer: UITapGestureRecognizer) {
       guard let toast = recognizer.view else { return }
       hideToastView(toast, fromTap: true)
   }
       
    // MARK: - 隐藏弹窗
    /**
     Hides the active toast. If there are multiple toasts active in a view, this method
     hides the oldest toast (the first of the toasts to have been presented).
     
     @see `hideAllToastViews()` to remove all active toasts from a view.
     
     @warning This method has no effect on activity toasts. Use `hideToastViewActivity` to
     hide activity toasts.
     
    */
    func hideToastView() {
        guard let activeToastView = activeToastViews.firstObject as? UIView else { return }
        hideToastView(activeToastView)
    }
    
    /**
     Hides an active toast.
     
     @param toast The active toast view to dismiss. Any toast that is currently being displayed
     on the screen is considered active.
     
     @warning this does not clear a toast view that is currently waiting in the queue.
     */
    func hideToastView(_ toast: UIView) {
        guard activeToastViews.contains(toast) else { return }
        hideToastView(toast, fromTap: false)
    }
    
    /**
     Hides all toast views.
     
     @param includeActivity If `true`, toast activity will also be hidden. Default is `false`.
     @param clearQueue If `true`, removes all toast views from the queue. Default is `true`.
    */
    func hideAllToastViews(includeActivity: Bool = false, clearQueue: Bool = true) {
        if clearQueue {
            clearToastViewQueue()
        }
        
        activeToastViews.compactMap { $0 as? UIView }
                    .forEach { hideToastView($0) }
    }
    
    /**
     Removes all toast views from the queue. This has no effect on toast views that are
     active. Use `hideAllToastViews(clearQueue:)` to hide the active toasts views and clear
     the queue.
     */
    func clearToastViewQueue() {
        queue.removeAllObjects()
    }
    
    // MARK: - Private Show/Hide Methods
    private func showViewToast(_ toast: UIView, duration: TimeInterval = TimeInterval(Int.max)) {
        activeToastViews.add(toast)
        self.addSubview(toast)
        UIView.animate(withDuration: ToastViewManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: {
            toast.alpha = 1.0
                }) { _ in
                    let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastViewTimerDidFinish(_:)), userInfo: toast, repeats: false)
                    RunLoop.main.add(timer, forMode: .common)
                    objc_setAssociatedObject(toast, &ToastViewKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                }

    }
    
    private func hideToastView(_ toast: UIView, fromTap: Bool) {
        if let timer = objc_getAssociatedObject(toast, &ToastViewKeys.timer) as? Timer {
            timer.invalidate()
        }
        
        UIView.animate(withDuration: ToastViewManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
            toast.alpha = 0.0
        }) { _ in
            toast.removeFromSuperview()
            self.activeToastViews.remove(toast)
            
            if let wrapper = objc_getAssociatedObject(toast, &ToastViewKeys.completion) as? ToastViewCompletionWrapper, let completion = wrapper.completion {
                completion(fromTap)
            }
            
            if let nextToastView = self.queue.firstObject as? UIView,
               let duration = objc_getAssociatedObject(nextToastView, &ToastViewKeys.duration) as? NSNumber {
                self.queue.removeObject(at: 0)
                self.showViewToast(nextToastView, duration: duration.doubleValue)
//                self.showViewToast(nextToastView, tap: tap.boolValue, point: point.cgPointValue, duration: duration.doubleValue, style: style)
//                self.showToastView(nextToastView, duration: duration.doubleValue, point: point.cgPointValue)
            }
        }
    }
    
    func hideToastViewByContentView(_ num: Int = 0) {
        guard let parentView = self.superview else { return }
        if parentView.tag == toastViewTag {
            parentView.superview?.hideToastView()
        }else {
            guard num < 5 else { return }
            let endNum = num + 1
            hideToastViewByContentView(endNum)
        }
    }
    
    // MARK: - Events
    
    @objc
    private func handleToastViewTapped(_ recognizer: UITapGestureRecognizer) {
        guard let toast = recognizer.view else { return }
        hideToastView(toast, fromTap: true)
    }
    
    @objc
    private func toastViewTimerDidFinish(_ timer: Timer) {
        guard let toast = timer.userInfo as? UIView else { return }
        hideToastView(toast)
    }
    
}

// MARK: - ToastView Style

/**
 `ToastViewStyle` instances define the look and feel for toast views created via the
 `makeToastView` methods as well for toast views created directly with
 `toastViewForMessage(message:title:image:style:)`.

 @warning `ToastViewStyle` offers relatively simple styling options for the default
 toast view. If you require a toast view with more complex UI, it probably makes more
 sense to create your own custom UIView subclass and present it with the `showToastView`
 methods.
*/
public struct ToastViewStyle {

    public init() {}
    
    /**
     The background color. Default is `.black` at 80% opacity.
    */
    public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
    
    /**
     The title color. Default is `UIColor.whiteColor()`.
    */
    public var titleColor: UIColor = .white
    
    /**
     The message color. Default is `.white`.
    */
    public var messageColor: UIColor = .white
    
    /**
     A percentage value from 0.0 to 1.0, representing the maximum width of the toast
     view relative to it's superview. Default is 0.8 (80% of the superview's width).
    */
    public var maxWidthPercentage: CGFloat = 0.8 {
        didSet {
            maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
        }
    }
    
    /**
     A percentage value from 0.0 to 1.0, representing the maximum height of the toast
     view relative to it's superview. Default is 0.8 (80% of the superview's height).
    */
    public var maxHeightPercentage: CGFloat = 0.8 {
        didSet {
            maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0)
        }
    }
    
    /**
     The spacing from the horizontal edge of the toast view to the content. When an image
     is present, this is also used as the padding between the image and the text.
     Default is 10.0.
     
    */
    public var horizontalPadding: CGFloat = 10.0
    
    /**
     The spacing from the vertical edge of the toast view to the content. When a title
     is present, this is also used as the padding between the title and the message.
     Default is 10.0. On iOS11+, this value is added added to the `safeAreaInset.top`
     and `safeAreaInsets.bottom`.
    */
    public var verticalPadding: CGFloat = 10.0
    
    /**
     The corner radius. Default is 10.0.
    */
    public var cornerRadius: CGFloat = 10.0;
    
    /**
     The title font. Default is `.boldSystemFont(16.0)`.
    */
    public var titleFont: UIFont = .boldSystemFont(ofSize: 16.0)
    
    /**
     The message font. Default is `.systemFont(ofSize: 16.0)`.
    */
    public var messageFont: UIFont = .systemFont(ofSize: 16.0)
    
    /**
     The title text alignment. Default is `NSTextAlignment.Left`.
    */
    public var titleAlignment: NSTextAlignment = .left
    
    /**
     The message text alignment. Default is `NSTextAlignment.Left`.
    */
    public var messageAlignment: NSTextAlignment = .left
    
    /**
     The maximum number of lines for the title. The default is 0 (no limit).
    */
    public var titleNumberOfLines = 0
    
    /**
     The maximum number of lines for the message. The default is 0 (no limit).
    */
    public var messageNumberOfLines = 0
    
    /**
     Enable or disable a shadow on the toast view. Default is `false`.
    */
    public var displayShadow = false
    
    /**
     The shadow color. Default is `.black`.
     */
    public var shadowColor: UIColor = .black
    
    /**
     A value from 0.0 to 1.0, representing the opacity of the shadow.
     Default is 0.8 (80% opacity).
    */
    public var shadowOpacity: Float = 0.8 {
        didSet {
            shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
        }
    }

    /**
     The shadow radius. Default is 6.0.
    */
    public var shadowRadius: CGFloat = 6.0
    
    /**
     The shadow offset. The default is 4 x 4.
    */
    public var shadowOffset = CGSize(width: 4.0, height: 4.0)
    
    /**
     The image size. The default is 80 x 80.
    */
    public var imageSize = CGSize(width: 80.0, height: 80.0)
    
    /**
     The size of the toast activity view when `makeToastViewActivity(position:)` is called.
     Default is 100 x 100.
    */
    public var activitySize = CGSize(width: 100.0, height: 100.0)
    
    /**
     The fade in/out animation duration. Default is 0.2.
     */
    public var fadeDuration: TimeInterval = 0.2
    
    /**
     Activity indicator color. Default is `.white`.
     */
    public var activityIndicatorColor: UIColor = .white
    
    /**
     Activity background color. Default is `.black` at 80% opacity.
     */
    public var activityBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
    
}

// MARK: - ToastView Manager

/**
 `ToastViewManager` provides general configuration options for all toast
 notifications. Backed by a singleton instance.
*/
public class ToastViewManager {
    
    /**
     The `ToastViewManager` singleton instance.
     
     */
    public static let shared = ToastViewManager()
    
    /**
     The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called
     with with a nil style.
     
     */
    public var style = ToastViewStyle()
    
    /**
     Enables or disables tap to dismiss on toast views. Default is `true`.
     
     */
    public var isTapToDismissEnabled = true
    
    /**
     Enables or disables queueing behavior for toast views. When `true`,
     toast views will appear one after the other. When `false`, multiple toast
     views will appear at the same time (potentially overlapping depending
     on their positions). This has no effect on the toast activity view,
     which operates independently of normal toast views. Default is `false`.
     
     */
    public var isQueueEnabled = false
    
    /**
     The default duration. Used for the `makeToastView` and
     `showToastView` methods that don't require an explicit duration.
     Default is 3.0.
     
     */
    public var duration: TimeInterval = 3.0
    
    /**
     Sets the default position. Used for the `makeToastView` and
     `showToastView` methods that don't require an explicit position.
     Default is `ToastViewPosition.Bottom`.
     
     */
    public var position: ToastViewPosition = .bottom
    
}

// MARK: - ToastViewPosition

public enum ToastViewPosition {
    case top
    case topNoPadding
    case center
    case bottom
    case bottomNoPadding
    
    fileprivate func centerPoint(forToastView toast: UIView, inSuperview superview: UIView) -> CGPoint {
        let topPadding: CGFloat = ToastViewManager.shared.style.verticalPadding + superview.csSafeAreaInsets.top
        let bottomPadding: CGFloat = ToastViewManager.shared.style.verticalPadding + superview.csSafeAreaInsets.bottom
        
        switch self {
        case .top:
            return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + topPadding)
        case .topNoPadding:
            return CGPoint(x: superview.bounds.size.width / 2.0, y: toast.frame.size.height / 2.0)
        case .center:
            return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0  - superview.csSafeAreaInsets.bottom)
        case .bottom:
            return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding)
        case .bottomNoPadding:
            return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height - (toast.frame.size.height / 2.0) - superview.csSafeAreaInsets.bottom)
        }
    }
}

// MARK: - Private UIView Extensions

private extension UIView {
    var csSafeAreaInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return self.safeAreaInsets
        } else {
            return .zero
        }
    }
}
